package com.echatim.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@ConditionalOnProperty(name="echatim.sdk.auth-type", havingValue="community")
@Component
public class HttpTopicInterceptor implements HandlerInterceptor {
    @Value("${cros.allow-origin}")
    private String allowOrigin;
    @Value("${cros.allow-methods}")
    private String allowMethods;
    @Value("${cros.allow-headers}")
    private String allowHeader;
    // 允许跨域
    private void enableCros(HttpServletResponse response){
        response.setHeader("Access-Control-Allow-Origin", allowOrigin);
        response.setHeader("Access-Control-Allow-Methods", allowMethods);
        response.addHeader("Access-Control-Allow-Headers", allowHeader);
        response.setHeader("Access-Control-Max-Age", "3600");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        enableCros(response);

        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

}
